package com.lwq.weatherapp.net;

import com.lwq.weatherapp.util.HiExecutor;
import com.lwq.weatherapp.util.HiNetUtil;
import ohos.hiviewdfx.HiLog;
import ohos.hiviewdfx.HiLogLabel;
import ohos.net.NetHandle;
import ohos.net.NetManager;
import org.devio.hi.json.HiJson;
import org.devio.hi.json.JSONException;
import org.devio.hi.json.JSONObject;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

/**
 *  请求接口实现类
 */
public class HiNet implements IHiNet{
    //网络请求器
    private NetManager netManager;
    //日志打印
    private HiLogLabel hiLogLabel = new HiLogLabel(0, 0, HiNet.class.getSimpleName());

    public HiNet() {
        netManager = NetManager.getInstance(null);
    }

    @Override
    public void get(String url, Map<String, String> params, NetListener listener) {
        String finalUrl = HiNetUtil.buildParams(url, params);
        HiLog.debug(hiLogLabel,"finalUrl: " + finalUrl);
        //创建新的线程
        HiExecutor.runBG(new Runnable() {
            @Override
            public void run() {
                doGet(finalUrl, listener);
            }
        });
    }

    /**
     *  发送get请求
     *  @param finalUrl
     *  @param listener
     */
    private void doGet(String finalUrl, NetListener listener) {
        NetHandle netHandle = netManager.getDefaultNet();
        HttpURLConnection connection = null;
        InputStream inputStream = null;
        ByteArrayOutputStream baos = null;
        try {
            URL url = new URL(finalUrl);
            URLConnection urlConnection = netHandle.openConnection(url, Proxy.NO_PROXY);
            //如果是http请求
            if (urlConnection instanceof HttpURLConnection) {
                connection = (HttpURLConnection) urlConnection;
            }
            connection.setRequestMethod("GET");
            connection.connect();
            HiLog.debug(hiLogLabel,"建立连接中......");
            if (connection.getResponseCode() == 200) {
                HiLog.debug(hiLogLabel, "getResponseCode() == 200");
                inputStream = connection.getInputStream();
                baos = new ByteArrayOutputStream();
                int readLen;
                byte[] bytes = new byte[1024];
                while ((readLen = inputStream.read(bytes)) != -1) {
                    baos.write(bytes, 0, readLen);
                }
                String result = baos.toString();
                HiExecutor.runUI(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            HiJson res = new HiJson(new JSONObject(result));
                            listener.onSuccess(res);
                            HiLog.debug(hiLogLabel, "success...");
                        } catch (JSONException e) {
                            e.printStackTrace();
                            listener.onFail("数据解析错误 msg: " + e.toString());
                        }
                    }
                });
            }else {
                HiLog.error(hiLogLabel, "请求失败 code: " + connection.getResponseCode());
                listener.onFail("请求失败 code: " + connection.getResponseCode());
            }
        }catch (Exception e) {
            HiLog.error(hiLogLabel, "请求失败 msg: " + e.toString());
            listener.onFail("请求失败 msg: " +  e.toString());
        }finally {
            //断开请求
             if (null != connection) {
                 connection.disconnect();
             }
             //关闭输入流
             HiNetUtil.close(inputStream);
             //关闭输出流
            HiNetUtil.close(baos);
        }
    }
}
